package com.myh.gulimall.product.service.impl;

import com.myh.common.constant.ProductConstant;
import com.myh.common.exception.BizCodeEnum;
import com.myh.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.myh.gulimall.product.service.AttrAttrgroupRelationService;
import com.myh.gulimall.product.service.AttrGroupService;
import com.myh.gulimall.product.service.CategoryService;
import com.myh.gulimall.product.vo.AttrInfoVo;
import com.myh.gulimall.product.vo.AttrQueryPageVo;
import com.myh.gulimall.product.vo.AttrVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.myh.common.utils.PageUtils;
import com.myh.common.utils.Query;

import com.myh.gulimall.product.dao.AttrDao;
import com.myh.gulimall.product.entity.AttrEntity;
import com.myh.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private AttrAttrgroupRelationService attrAttrgroupRelationService;

    @Autowired
    private AttrGroupService attrGroupService;

    @Override
    public PageUtils queryPage(Map<String, Object> params, Long catelogId, String attrType) {
        String key = (String) params.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("attr_type", "base".equalsIgnoreCase(attrType) ? ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode() : ProductConstant.AttrEnum.ATTR_TYPE_SALE.getCode());
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        if (catelogId != 0) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("catelog_id", catelogId);
            });
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                queryWrapper);
        List<AttrEntity> records = page.getRecords();
        List<AttrQueryPageVo> list = records.stream().map((attrEntity) -> {
            Long attrId = attrEntity.getAttrId();
            Long id = attrEntity.getCatelogId();
            AttrQueryPageVo attrQueryPageVo = new AttrQueryPageVo();
            BeanUtils.copyProperties(attrEntity, attrQueryPageVo);
            attrQueryPageVo.setCatelogName(categoryService.findCatelogPathName(id));
            if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
                Long attrGroupIdByAttrId = attrAttrgroupRelationService.getAttrGroupIdByAttrId(attrId);
                if (attrGroupIdByAttrId != null) {
                    String name = attrGroupService.getNameByAttrGroupId(attrGroupIdByAttrId);
                    attrQueryPageVo.setGroupName(name);
                }
            }
            return attrQueryPageVo;
        }).collect(Collectors.toList());
        return new PageUtils(list, (int) page.getTotal(), (int) page.getSize(), (int) page.getCurrent());
    }


    @Override
    @Transactional
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        attrDao.insert(attrEntity);
        if (attr.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {   //只有基本属性才会保存AttrGroupId
            //mp的功能，主键返回，即插入后可立即获得主键id
            attrAttrgroupRelationService.saveAttrAttrgroupRelation(attrEntity.getAttrId(), attr);
        }

    }

    @Override
    public AttrInfoVo getAttrInfoById(Long attrId) {
        AttrEntity attrEntity = attrDao.selectById(attrId);
        AttrInfoVo attrInfoVo = new AttrInfoVo();
        BeanUtils.copyProperties(attrEntity, attrInfoVo);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            attrInfoVo.setAttrGroupId(attrAttrgroupRelationService.getAttrGroupIdByAttrId(attrId));
        }
        attrInfoVo.setCatelogPath(categoryService.findCatelogPath(attrEntity.getCatelogId()));
        return attrInfoVo;
    }

    @Override
    @Transactional
    public void updateAttrById(AttrInfoVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        attrDao.updateById(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            Integer count = attrAttrgroupRelationService.selectCountByAttrId(attr.getAttrId());
            if (count == 0) {
                //在修改时新增
                AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
                entity.setAttrGroupId(attr.getAttrGroupId());
                entity.setAttrId(attr.getAttrId());
                attrAttrgroupRelationService.save(entity);
            } else {
                //修改属性分组字段--attrGroupId
                attrAttrgroupRelationService.updateAttrGroupIdByAttrId(attr.getAttrId(), attr.getAttrGroupId());
            }

        }
    }

    /**
     * 获取属性分组没有关联的其他属性
     *
     * @param attrgroupId
     * @param params
     * @return
     */
    @Override
    public PageUtils getNoRelationAttr(Long attrgroupId, Map<String, Object> params) {
        String key = (String) params.get("key");
        //匹配catelog_id  attr_type = 1
        Long catelogId = attrGroupService.getCatelogIdByAttrGroupId(attrgroupId);
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.eq("attr_id", key).or().like("attr_name", key);
        }
        queryWrapper.eq("catelog_id", catelogId).eq("attr_type", ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode());
        List<AttrEntity> attrEntities = attrDao.selectList(queryWrapper);
        //过滤掉pms_attr_attrgroup_relation表当中含有的attr_id
        List<Long> attrIds = attrAttrgroupRelationService.getAttrIds(attrEntities);
        queryWrapper.notIn("attr_id", attrIds);
        IPage<AttrEntity> page = attrDao.selectPage(
                new Query<AttrEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public String queryAttrNameByAttrId(Long attrId) {
        AttrEntity attrEntity = attrDao.selectById(attrId);
        if (!Objects.isNull(attrEntity)){
            return attrEntity.getAttrName();
        } else {
            return null;
        }
    }

    @Override
    public Integer getSearchTypeByAttrId(Long attrId) {
        AttrEntity attrEntity = attrDao.selectById(attrId);
        if (!Objects.isNull(attrEntity)){
            return attrEntity.getSearchType();
        }
        return 0;
    }

}